package com.appbee.article.client.ui;

import javax.inject.Inject;

import com.appbee.article.client.presenter.ArticleBoxPresenter;
import com.appbee.core.client.templates.CommonTemplates;
import com.google.gwt.dom.client.EventTarget;
import com.google.gwt.dom.client.InputElement;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.Widget;

public class EditableText extends Widget implements ArticleBoxPresenter.View
{
	private final ArticleBoxPresenter presenter;
	private boolean canEdit;
	private final CommonTemplates htmlTemplate;
	private final IArticleStyle articleStyle;

	@Inject
	public EditableText(ArticleBoxPresenter presenter,
						IArticleStyle articleStyle,
						CommonTemplates htmlTemplate)
	{
		this.presenter = presenter;
		this.articleStyle = articleStyle;
		this.htmlTemplate = htmlTemplate;
		presenter.setView(this);
		setElement(DOM.createElement("h1"));
		setStyleName(articleStyle.editText());
		sinkEvents(Event.ONCLICK);
	}


	@Override
	public void showContent(String content)
	{
		SafeHtmlBuilder sb = new SafeHtmlBuilder();
		sb.appendEscaped(content == null ? "" : content);

		if (canEdit)
		{
			sb.append(htmlTemplate.button(	articleStyle.editButton(),
											"edit",
											"Breyta",
											"Breyta"));
		}

		getElement().setInnerHTML(sb.toSafeHtml().asString());
	}

	@Override
	public void edit(String content)
	{
		SafeHtmlBuilder sb = new SafeHtmlBuilder();
		sb.append(htmlTemplate.input("", "text", "", content == null ? ""
				: content));

		getElement().setInnerHTML(sb.toSafeHtml().asString());
		Element inputElement = getElement().getChild(0).cast();
		inputElement.focus();
		DOM.sinkEvents(inputElement, Event.ONBLUR | Event.ONKEYDOWN);

	}

	@Override
	public void setCanEdit(boolean canEdit)
	{
		this.canEdit = canEdit;
	}

	@Override
	public void onBrowserEvent(Event event)
	{
		String type = event.getType();
		EventTarget eventTarget = event.getEventTarget();
		if (!Element.is(eventTarget))
		{
			return;
		}
		final Element target = event.getEventTarget().cast();

		if ("click".equals(type) && "BUTTON".equals(target.getTagName()))
		{
			presenter.onEdit();
		}
		else if (("blur".equals(type) || ("keydown".equals(type) && event
				.getKeyCode() == KeyCodes.KEY_ENTER))

		&& "INPUT".equals(target.getTagName()))
		{
			InputElement inputElement = target.cast();
			presenter.onSave(inputElement.getValue());
		}

		super.onBrowserEvent(event);
	}

	@Override
	public void showLoadingIndicator()
	{
	}

	public void setStrId(String strId)
	{
		presenter.setStrId(strId);
	}

}
